import React from 'react'
import {Button, Divider, Row, message} from 'antd'
import {FormattedMessage} from 'react-intl'
import OrganizationList from './orgranization-list'
import {connect} from 'react-redux'
import {addOrganization, editOrganization, getOrganizations} from "../../actions/organization"
import NewOrganizationModal from './new-organization-modal'
import EditOrganizationModal from './edit-organization-modal'

class OrganizationBody extends React.Component {

  state = {
    currentPage: 1,
    isNewModalOpen: false,
    isEditModalOpen: false,
    organization: {}
  }

  componentDidMount = () => {
    const {currentPage} = this.state
    this.props.getOrganizations(currentPage)
  }

  closeModal = () => {
    this.setState({
      isNewModalOpen: false,
      isEditModalOpen: false
    })
  }

  addOrganization = organization => {
    const {currentPage} = this.state
    this.props.addOrganization(organization, () => {
      message.success('添加成功')
      this.closeModal()
      this.props.getOrganizations(currentPage)
    })
  }

  editOrganization = organization => {
    const {currentPage} = this.state
    this.props.editOrganization(organization, () => {
      message.success('编辑成功')
      this.closeModal()
      this.props.getOrganizations(currentPage)
    })
  }

  openEditModal = organization => {
    this.setState({
      organization,
      isEditModalOpen: true
    })
  }

  changePage = currentPage => {
    this.setState({currentPage}, () => {
      this.props.getOrganizations(currentPage)
    })
  }

  render() {
    const {organizationPage} = this.props
    const {currentPage, isNewModalOpen,isEditModalOpen,organization} = this.state
    return <div>
      <Row>
        <Button type='primary' onClick={() => this.setState({isNewModalOpen: true})}>
          <FormattedMessage id='新增'/></Button>
      </Row>
      <Divider/>
      <OrganizationList
        currentPage={currentPage}
        organizationPage={organizationPage}
        openEditModal={this.openEditModal}
        changePage={this.changePage}
      />

      <NewOrganizationModal
        isNewModalOpen={isNewModalOpen}
        addOrganization={organization => this.addOrganization(organization)}
        closeModal={this.closeModal}
      />

      <EditOrganizationModal
        organization={organization}
        closeModal={this.closeModal}
        isEditModalOpen={isEditModalOpen}
        editOrganization={organization => this.editOrganization(organization)}
      />
    </div>
  }
}

const mapStateToProps = ({organizationPage}) => ({
  organizationPage
})
const mapDispatchToProps = dispatch => ({
  getOrganizations: currentPage => dispatch(getOrganizations(currentPage)),
  addOrganization: (organization, callback) => dispatch(addOrganization(organization, callback)),
  editOrganization: (organization, callback) => dispatch(editOrganization(organization, callback))

})
export default connect(mapStateToProps, mapDispatchToProps)(OrganizationBody)